<template>
  <div>
    <BreadCrumbs name1="用户管理" name2="用户列表" name3="用户详情" />

    <!-- 基础信息 -->
    <div style="display: flex; justify-content: space-between; margin-bottom: 10px">
      <div>
        <el-button type="text" @click="$router.go(-1)">返回</el-button>
        <el-button
          type="text"
          icon="el-icon-edit"
          @click="saveBasicInfo"
          >{{ isBasicEdit ? '保存' : '编辑' }}</el-button
        >
      </div>
    </div>
    <el-divider />

    <el-descriptions title="基础信息" :column="1">
      <el-descriptions-item label="用户手机号">
        {{ detail.phone }}
      </el-descriptions-item>

      <el-descriptions-item label="用户性别">
        <el-select v-if="isBasicEdit" v-model="detail.gender" size="small">
          <el-option label="男" value="MALE" />
          <el-option label="女" value="FEMALE" />
        </el-select>
        <span v-else>
          {{ detail.gender === 'MALE' ? '男' : detail.gender === 'FEMALE' ? '女' : '其他' }}
        </span>
      </el-descriptions-item>

      <el-descriptions-item label="用户名">
        <el-input v-if="isBasicEdit" v-model="detail.name" size="small" />
        <span v-else>{{ detail.name }}</span>
      </el-descriptions-item>

      <el-descriptions-item label="合并症">
        <span v-if="!detail.comorbidities?.length">--</span>
        <el-tag
          v-for="item in detail.comorbidities"
          :key="item"
          style="margin-right: 6px"
          type="info"
          size="small"
        >
          {{ item }}
        </el-tag>
      </el-descriptions-item>
    </el-descriptions>

    <el-divider />

    <!-- 表格 -->
    <el-table :data="tableData" stripe border size="mini" style="width: 100%">
      <el-table-column prop="created" label="打卡时间" width="120" align="center">
        <template slot-scope="scope">
          {{ new Date(scope.row.created).toLocaleDateString() }}
        </template>
      </el-table-column>

      <el-table-column prop="mealType" label="餐次" align="center">
        <template slot-scope="scope">
          {{ getMealTypeName(scope.row.mealType) }}
        </template>
      </el-table-column>

      <el-table-column prop="foods" label="食物" align="center">
        <template slot-scope="scope">
          <el-input
            v-if="editRows[scope.$index]"
            v-model="scope.row.foods"
            size="small"
          />
          <span v-else>{{ scope.row.foods }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="calorie" label="热量" align="center">
        <template slot-scope="scope">
          <el-input
            v-if="editRows[scope.$index]"
            v-model="scope.row.calorie"
            size="small"
          />
          <span v-else>{{ scope.row.calorie }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="protein" label="蛋白质" align="center">
        <template slot-scope="scope">
          <el-input
            v-if="editRows[scope.$index]"
            v-model="scope.row.protein"
            size="small"
          />
          <span v-else>{{ scope.row.protein }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="fat" label="脂肪" align="center">
        <template slot-scope="scope">
          <el-input
            v-if="editRows[scope.$index]"
            v-model="scope.row.fat"
            size="small"
          />
          <span v-else>{{ scope.row.fat }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="carbohydrate" label="碳水化合物" align="center">
        <template slot-scope="scope">
          <el-input
            v-if="editRows[scope.$index]"
            v-model="scope.row.carbohydrate"
            size="small"
          />
          <span v-else>{{ scope.row.carbohydrate }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="inflammatory" label="炎症感" align="center">
        <template slot-scope="scope">
          <el-input
            v-if="editRows[scope.$index]"
            v-model="scope.row.inflammatory"
            size="small"
          />
          <span v-else>{{ scope.row.inflammatory }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="score" label="积分" align="center">
        <template slot-scope="scope">
          <el-input-number
            v-if="editRows[scope.$index]"
            v-model="scope.row.score"
            :min="0"
            size="small"
          />
          <span v-else>{{ scope.row.score }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="100" align="center">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="toggleRowEdit(scope.$index)"
          >
            {{ editRows[scope.$index] ? '保存' : '编辑' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      /* 基础信息 */
      isBasicEdit: false,
      detail: {
        phone: '00000000000',
        gender: 'MALE',
        name: '示例',
        comorbidities: [
          { id: 1, name: '高血压' },
          { id: 2, name: '糖尿病' }
        ]
      },

      /* 表格 */
      editRows: {}, // { 0: true, 2: true } 表示第 0、2 行在编辑
      tableData: []
    };
  },

  methods: {
    /* 拉取用户详情 + 打卡记录 */
    async getDataRecords() {
      const { data, msg, code } = await this.$http.get(
        `/diet/admin/user/${this.$route.params.id}`
      );
      if (code) return this.$message.error(msg);

      // 基础信息
      this.detail = {
        userId: data.userId,
        phone: data.phone,
        name: data.name,
        gender: data.gender,
        comorbidities: data.comorbidities || []
      };

      // 构造 tableData
      this.tableData = this.buildTableData(data.punch || []);
    },

    /* 把后端 punch → 前端 tableData */
    buildTableData(punchList) {
      return punchList.map(p => {
        // 食物名称拼接
        const foods = (p.punchFood || []).map(f => f?.food?.name || '未知').join('、');
        
        // 营养素：这里取第一条 punchFood 的微元素，你也可以自定义合并规则
        const m = (p.punchFood || [])[0]?.food?.microElement || {};
        
        return {
          created: p.punchDate,
          mealType: p.mealType,
          foods: foods || '--',
          calorie: `${Math.round(m.caloriesPerGram || 0)}千卡`,
          protein: `${Math.round(m.proteinPerGram || 0)}克`,
          fat: `${Math.round(m.fatPerGram || 0)}克`,
          carbohydrate: `${Math.round(m.carbsPerGram || 0)}克`,
          inflammatory: p.inflammatory || '--',
          score: p.point?.count || 0
        };
      });
    },

    /* 获取餐次名称 */
    getMealTypeName(mealType) {
      switch (mealType) {
        case 'BREAKFAST': return '早餐';
        case 'LUNCH': return '午餐';
        case 'DINNER': return '晚餐';
        case 'SNACK': return '加餐';
        default: return mealType;
      }
    },

    /* 保存基础信息 */
    async saveBasicInfo() {
      if (this.isBasicEdit) {
        const update = {
          userId: this.$route.params.id,
          name: this.detail.name,
          gender: this.detail.gender
        };
        try {
          await this.$http.post('/diet/admin/user/update', update);
          this.$message.success('基础信息保存成功');
          await this.getDataRecords(); // 更新数据
        } catch (error) {
          this.$message.error('保存失败');
          console.error(error);
        }
      }
      this.isBasicEdit = !this.isBasicEdit;
    },

    /* 表格行编辑 / 保存 */
    async toggleRowEdit(index) {
      if (this.editRows[index]) {
        try {
          // 这里可以根据需求调整保存逻辑
          await this.$http.post('/api/user/update/daily', {
            userId: this.detail.userId,
            daily: this.tableData[index]
          });
          this.$message.success('该行已保存');
        } catch (error) {
          this.$message.error('保存失败');
          console.error(error);
        }
      }
      this.$set(this.editRows, index, !this.editRows[index]);
    }
  },

  async mounted() {
    await this.getDataRecords();
  }
};
</script>

<style lang="less" scoped>
::v-deep .el-descriptions-item {
  padding-bottom: 24px !important;
}
</style>